import React, { useRef, useState, useEffect } from 'react';
import Webcam from 'react-webcam';
import {post} from '../../../axios/request'
// import './App.css'; // 假设你有一个CSS文件来处理样式  
const LiveDetection = () => {
    useEffect(() => {
        if(imageBase64){
            face()
        }
    })
    const webcamRef = useRef(null);
    const [imageBase64, setImageBase64] = useState(null);
    const imageUrlToBase64 = (url, callback) => {
        const img = new Image();
        img.crossOrigin = 'Anonymous'; // 如果图像来自不同的源，则需要这个属性来允许跨源请求  
        img.onload = () => {
            const canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0);
            const base64Image = canvas.toDataURL('image/jpeg'); // 将图像转换为base64格式的JPEG图像  
            callback(base64Image);
        };
        img.src = url;
    };
    // 摄像头视频流被捕获时触发的回调  
    const capture =() => {
            const imgSrc = webcamRef.current.getScreenshot();
            console.log(imgSrc)
            imageUrlToBase64(imgSrc, (base64Image) => {
                setImageBase64(base64Image.split(',')[1]); // 更新状态以存储base64编码的图像数据  
                // 发送base64编码的图像数据到后端进行活体检测  
            });
        }
 
    const face = async () => {
        try {  
            let { code } = await post('/users/face-verification', { image: imageBase64 });  
            if (code === 200) {  
                alert('人脸识别成功');  
            } else {  
                alert('人脸识别失败');  
            }  
        } catch (error) {  
            console.error('网络请求错误:', error);  
            alert('网络请求失败');  
        }  
    }

    return (
        <div className="App">
            <h1>活体检测示例</h1>
            <Webcam
                audio={false}
                height={480}
                ref={webcamRef}
                screenshotFormat="image/jpeg"
                width={640}
                onCapture={capture}
            />
            <button onClick={capture}>捕捉图像并进行检测</button>
        </div>
    );
};

export default LiveDetection;